package nc.bs.servlet;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import nc.bs.dao.BaseDAO;
import nc.bs.framework.adaptor.IHttpServletAdaptor;
import nc.bs.framework.common.InvocationInfoProxy;
import nc.bs.framework.common.NCLocator;
import nc.bs.framework.server.ISecurityTokenCallback;
import nc.jdbc.framework.processor.MapListProcessor;
import nc.vo.pub.BusinessException;
import ncc.bs.utils.GetParamConfigUtil;
import ncc.bs.utils.GloableConfigParam;
import ncc.bs.utils.InputLogger;
import ncc.bs.utils.ResultMessage;
import nc.itf.pub.service.INCCAttachSyncService;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

@SuppressWarnings("restriction")
/**
 * 描述:附件同步接口
 * @autor : wangyong
 * @date : 2018/10/23
 */
public class yonyouNccAttachService extends HttpServlet implements IHttpServletAdaptor {
	private static final String logName = "oalog";
	private BaseDAO baseDAO;
	private INCCAttachSyncService NCCAttachSyncService;


	@Override
	public void doAction(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		InputLogger.info(logName,"begin-------->1、附件传输准备");
		resp.setContentType("application/json;charset=utf-8");
		resp.setCharacterEncoding("UTF-8");
		req.setCharacterEncoding("UTF-8");
		PrintWriter pw = resp.getWriter();
		try {
			NCLocator.getInstance().lookup(ISecurityTokenCallback.class).token("NCSystem".getBytes(),"pfxx".getBytes());
			String dataSource = GetParamConfigUtil.queryGroupSysParam(GloableConfigParam.NCC_DATASOURCE);
			InvocationInfoProxy.getInstance().setUserDataSource(dataSource);
			InputLogger.info(logName,"--------2、第三方请求NCC调用的方法【yonyouNccAttachService】数据库模拟登陆完成：数据源="+dataSource );
			// 读取请求体中的参数
			StringBuilder requestBody = new StringBuilder();
			String line;
			BufferedReader reader = req.getReader();
			while ((line = reader.readLine()) != null) {
				requestBody.append(line);
			}
			// 解析JSON参数
			if (requestBody == null || requestBody.length() < 1) {
				throw new Exception("请求参数body不允许为空！");
			}
			JSONObject param = JSONObject.parseObject(requestBody.toString());
			this.checkParam(param);
			String billtype = param.getString("biltype");  // 单据类型
			String sender = param.getString("sender");  // 单据类型
			String billcode = param.getString("billcode"); // 三方系统单据号
			JSONArray datas = param.getJSONArray("data");
			String sql = "";
			if("I2".equalsIgnoreCase(billtype)){
				sql = String.format("SELECT pk_group,pk_org,cbillid pk_bill,creator  from ia_i2bill where dr = 0 and vdef1 = '%s'", billcode);
			}else if ("I6".equalsIgnoreCase(billtype)){
				sql = String.format("SELECT pk_group,pk_org,cbillid pk_bill,creator  from ia_i6bill where dr = 0 and vdef1 = '%s'", billcode);
			} else if ("TTPZD".equalsIgnoreCase(billtype)) {
				sql = String.format("select pk_group,pk_org,pk_voucher pk_bill, creator   from gl_sscvoucher where dr = 0 and  def2 = '%s'", billcode);
			}else if ("cmppaybill".equals(billtype)){
				sql = String.format("SELECT DISTINCT\n" +
						"\txlog.BUSIBILL billno,cmp.pk_group, cmp.pk_org, cmp.pk_PAYBILL pk_bill,cmp.creator \n" +
						"FROM\n" +
						"\tXX_XLOG xlog\n" +
						"LEFT JOIN CMP_PAYBILL cmp ON xlog.BUSIBILL = cmp.BILL_NO \n" +
						"WHERE\n" +
						"\txlog.dr = 0 \n" +
						"\tAND xlog.CORRECT = 'Y' \n" +
						"\tAND xlog.DOC_SOURCE = '%s' \n" +
						"\tAND xlog.doc_id = '%s' ",sender, billcode);
			} else{
				throw new Exception("单据类型【"+billtype+"】不支持！");
			}
			List<Map<String,Object>> lists = (List<Map<String,Object>>)this.getBaseDAO().executeQuery(sql, new MapListProcessor());
			if (lists == null || lists.isEmpty()) throw new Exception("单据类型【"+billtype+"】,对应的业务单据号【"+billcode+"】HRP系统不存在！");
			Map<String, Object> map = lists.get(0);
			String pk_group = map.get("pk_group").toString();
			String pk_org = map.get("pk_org").toString();
			String pk_bill = map.get("pk_bill").toString();
			String creator = map.get("creator").toString();
			this.getNCCAttachSyncService().fileUploadFileBase64(pk_group, pk_org, pk_org,billtype, pk_bill,creator,datas);
			JSONObject res = ResultMessage.success(datas, "附件上传成功");
			InputLogger.info(logName,"end-------->附件上传成功,单据类型:【"+billtype+"】,第三方业务单据号:【"+billcode+"】");
			pw.println(res);
			pw.flush();
		}catch(Exception e) {
			String message = "--------附件上传异常异常信息:  "+e.getMessage();
			InputLogger.error(logName, message);
			JSONObject error = ResultMessage.error(message, e);
			pw.println(error);
			return;
		}
        InputLogger.info(logName,"end-------->第三方系统开始调用NCC单登陆结束【nc.bs.oa.servlet.yonyouHOPService】 ");
	}

	@Override
	protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doAction(req, resp);
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doAction(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doAction(req, resp);
	}

	@Override
	protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doAction(req, resp);
	}

	public BaseDAO getBaseDAO() {
		if(null == baseDAO) {
			baseDAO = new BaseDAO(InvocationInfoProxy.getInstance().getUserDataSource());
		}
		return baseDAO;
	}

	/**
	 * 检查请求参数 格式是否正确
	 * @param json
	 * @throws BusinessException
	 */
	private  void checkParam(JSONObject json) throws BusinessException{
        StringBuilder error = new StringBuilder();
		if("".equals(json.getString("biltype")) || null == json.getString("biltype")) {
            error.append("业务单据类型【biltype】 不允许为空");
        }
		if("".equals(json.getString("billcode")) || null == json.getString("billcode") ) {
			error.append("业务单据号【billcode】不允许为空！");
		}
		JSONArray data = json.getJSONArray("data");
		if("".equals(data) || data.isEmpty() ){
			error.append("请求参数中【data】中不允许为空");
		}
		for (Object item : data) {
			if (null == item || "".equals(item.toString())){
				error.append("请求参数中【data】中明细不允许为空");
				continue;
			}
			JSONObject itemJson = JSONObject.parseObject(item.toString());
			if("".equals(itemJson.getString("content")) || itemJson.getString("content") == null ) {
				error.append("请求参数中【data】明细中 附件内容不允许为空!");
			}
			if("".equals(itemJson.getString("filename")) || itemJson.getString("filename") == null) {
				error.append("请求参数中【data】明细中 附件名称 不允许为空!");
			}
			if("".equals(itemJson.getString("filetype")) || itemJson.getString("filetype") == null) {
				error.append("请求参数中【data】明细中 附件类型 不允许为空!");
			}
		}

        if(error.toString().length() > 0 ) throw new BusinessException(error.toString());
    }

	public INCCAttachSyncService getNCCAttachSyncService() {
        if (this.NCCAttachSyncService == null) {
            this.NCCAttachSyncService = NCLocator.getInstance().lookup(INCCAttachSyncService.class);
        }
		return this.NCCAttachSyncService;
	}
}
